package com.mayn.jst.login;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mayn.jst.shop.action.ShopAccountAction;
import com.mayn.jst.shop.action.ShopAction;
import com.mayn.jst.shop.model.ShopAccountModel;
import com.mayn.util.DriverFactory;
import com.mayn.util.HttpUtil;
import com.mayn.util.ProcessUtil;
import com.mayn.util.RegUtil;
import com.mayn.util.SendCloudMailUtil;
import com.mayn.util.WebDriverUtil;
import com.mayn.util.XsoupUtils;

import net.sf.json.JSONObject;

public class JdLoginAction {

	private static final Logger LOG = LoggerFactory.getLogger(JdLoginAction.class);

	static String loginUrl = "https://passport.jd.com/common/loginPage?from=pop_vender&regTag=2&ReturnUrl=https://shop.jd.com/index.action";

	static int maxWaitTime = 1800000;//1000 * 60 * 30 = 30 分钟

	/**
	 * 检查指定店铺的cookie是否依然生效
	 * 
	 * @param shopId
	 * @return
	 */
	public static boolean checkAndSaveJdLoginCookie(int shopId) {
		String shopName = ShopAction.getShop(shopId).getStr("SHOP_NAME");
		String cookie = ShopAccountAction.getShopAccountCookie(shopId);
		LOG.info("开始检查店铺cookie有效性--" + shopName);
		if (cookie == null || cookie.equals("") || (!checkJdLoginCookie(cookie))) {
			LOG.info("当前店铺cookie已失效，需重新获取--" + shopName);
			cookie = getJdLoginCookieStr(shopId);
			if (checkJdLoginCookie(cookie)) {
				ShopAccountAction.saveShopAccountCookie(shopId, cookie, 1);
				LOG.info("当前店铺cookie重新获取成功--" + shopName);
				return true;
			} else {
				LOG.error("当前店铺cookie重新获取失败--" + shopName);
				ShopAccountAction.saveShopAccountCookie(shopId, cookie, 2);
			}
		} else {
			LOG.info("当前店铺cookie依然有效--" + shopName);
			return true;
		}
		return false;
	}

	/**
	 * 检查京东cookie是否失效
	 * 
	 * @return
	 */
	public static Boolean checkJdLoginCookie(String cookie) {
		try {
			String url = "https://shop.jd.com/json/index/getShopDatas.action";

			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("Cache-Control", "no-cache");
			headers.put("Connection", "keep-alive");
			headers.put("Cookie", cookie);
			headers.put("Host", "shop.jd.com");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");

			String resp = "";
			resp = HttpUtil.sendGetWithURLConnection(url, null, headers);
			if (resp.trim().startsWith("{")) {
				JSONObject object = JSONObject.fromObject(resp.trim());
				if (object.containsKey("todayDatas")) {
					return true;
				}
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 登陆京东后台返回cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static String getJdLoginCookieStr(int shopId) {
		return HttpUtil.getCookieStr(getJdLoginCookie(shopId));

	}

	/**
	 * 登陆京东后台返回cookie
	 * 
	 * @param userName
	 * @param userPass
	 * @return
	 */
	public static String getJdLoginCookieStr(String userName, String userPass) {
		return HttpUtil.getCookieStr(getJdLoginCookie(userName, userPass));

	}

	/**
	 * 登陆京东后台返回cookie
	 * 
	 * @param shopId
	 * @return
	 */
	public static Set<Cookie> getJdLoginCookie(int shopId) {
		String userName = "";
		String userPass = "";
		if (shopId > 0) {
			ShopAccountModel shopAccount = ShopAccountAction.getShopAccount(shopId);
			if (shopAccount != null) {
				userName = shopAccount.getStr("SA_SHOP_USERNAME");
				userPass = shopAccount.getStr("SA_SHOP_USERPASS");
			}
		} else {
			LOG.error("shopId参数错误:" + shopId);
			return null;
		}
		return getJdLoginCookie(userName, userPass);
	}

	/**
	 * 登陆京东后台返回cookie
	 * 
	 * @param userName
	 * @param userPass
	 * @return
	 */
	public static Set<Cookie> getJdLoginCookie(String userName, String userPass) {

		Set<Cookie> cookieSet = null;
		WebDriver driver = null;
		try {
			ChromeOptions options = new ChromeOptions();
			// 设置user agent为iphone5
			options.addArguments(
					"--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");
			driver = DriverFactory.getWebDriver(options);

			driver.get(loginUrl);
			By by = null;

			String title = driver.getTitle();
			LOG.info(title);

			WebElement loginBox = driver.findElement(By.id("formloginframe"));
			if (loginBox != null) {

				ProcessUtil.ThreadSleep(1000);
				by = By.xpath("//input[@name='loginname']");
				WebElement user = driver.findElement(by);
				if (user != null) {
					WebDriverUtil.moveToElementAndClick(driver, by);
					user.clear();
					user.sendKeys(userName);
				}
				ProcessUtil.ThreadSleep(3000);
				by = By.xpath("//input[@name='nloginpwd']");
				WebElement password = driver.findElement(by);
				if (password != null) {
					WebDriverUtil.moveToElementAndClick(driver, by);
					password.clear();
					password.sendKeys(userPass);
				}
				ProcessUtil.ThreadSleep(800);

				by = By.id("paipaiLoginSubmit");
				WebElement submit = driver.findElement(by);
				if (submit != null) {
					WebDriverUtil.moveToElementAndClick(driver, by);
				}
			}
			ProcessUtil.ThreadSleep(500);
			LOG.debug(driver.getCurrentUrl());
			int sleepMs = 0;
			while (true) {
				if (HttpUtil.getHost(driver.getCurrentUrl()).equals("shop.jd.com")) {
					break;
				} else {
					sleepMs += 1000;
					LOG.info("还未登录成功,等待1000ms --" + driver.getCurrentUrl());
					ProcessUtil.ThreadSleep(1000);
					// 等待人工登录干预
					if (sleepMs == 1000 * 60 * 3) {
						String msg = "京东登陆不成功,需要人工干预--" + driver.getCurrentUrl();
						LOG.info(msg);
						SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
					}
					if (sleepMs >= maxWaitTime) {
						String msg = "京东登陆不成功,已等待" + maxWaitTime + "毫秒,退出运行 --" + driver.getCurrentUrl();
						LOG.info(msg);
						SendCloudMailUtil.sendMailCode(msg, "dadao@iningmei.com");
						break;
					}
				}
			}
			LOG.info("登录成功--" + driver.getCurrentUrl());
			cookieSet = driver.manage().getCookies();
			for (Cookie ck : cookieSet) {
				LOG.debug(ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";"
						+ ck.getExpiry() + ";" + ck.isSecure());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null) {
				driver.quit();
			}
		}

		return cookieSet;

	}

	/**
	 * 京东店铺费用
	 * 
	 * @param cookie
	 * @return
	 */
	public static Map<String, Object> getJdShopFee(String cookie) {

		Map<String, Object> map = new HashMap<String, Object>();
		try {

			String url = "https://fin.shop.jd.com/finance/fsp/detail_getStatementSummaryInfo.action?query.venderId=49508&query.statementStartDate=2017-03-20&type=old";

			HashMap<String, String> headers = new HashMap<String, String>();
			headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			headers.put("Cache-Control", "no-cache");
			headers.put("Connection", "keep-alive");
			headers.put("Cookie", cookie);
			headers.put("Host", "fin.shop.jd.com");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36");

			String resp = "";
			resp = HttpUtil.sendGetWithURLConnection(url, null, headers);
			LOG.debug(resp.trim());

			String regex = "";
			regex = "//div[@class='account']";
			String accountContent = XsoupUtils.GetXsoupStr(resp, regex);
			// 京豆
			String regex1 = "([^=]+)(?:\\(京豆\\))";
			String content1 = RegUtil.GetRegStr(accountContent, regex1, 1).trim().replace(" ", "").replace("元", "");
			LOG.info("京豆=" + content1);
			map.put("jingdou", Double.parseDouble(content1));
			// 京挑客服务费
			String regex2 = "([^=]+)(?:\\(京挑客服务费\\))";
			String content2 = RegUtil.GetRegStr(accountContent, regex2, 1).trim().replace(" ", "").replace("元", "");
			LOG.info("京挑客服务费=" + content2);
			map.put("jingtiaoke", Double.parseDouble(content2));
			// 佣金
			String regex3 = "([^\\)]+)(?:\\(佣金\\))";
			String content3 = RegUtil.GetRegStr(accountContent, regex3, 1).trim().replace(" ", "").replace("元", "");
			LOG.info("佣金=" + content3);
			map.put("yongjin", Double.parseDouble(content3));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return map;
	}

}
